package mcp

import (
	"fmt"
	"project-info/src/model"
	"strconv"

	"project-info/src/lib")

// GitLab相关处理器
func handleListGitlabProjects(c *lib.GinContext, args map[string]interface{}) *MCPToolResult {
	limit := getIntParam(args, "limit", 10)
	search := getStringParam(args, "search", "")
	namespace := getStringParam(args, "namespace", "")

	var repos []model.GitlabRepo
	db := model.DB().Limit(limit)

	if search != "" {
		db = db.Where("project_name LIKE ? OR project_http_url LIKE ?", "%"+search+"%", "%"+search+"%")
	}
	if namespace != "" {
		db = db.Where("name_space = ?", namespace)
	}

	result := db.Find(&repos)
	if result.Error != nil {
		return createErrorResult("数据库查询失败: " + result.Error.Error())
	}

	content := fmt.Sprintf("找到 %d 个GitLab项目:\n\n", len(repos))
	for _, repo := range repos {
		content += fmt.Sprintf("- **%s** (%s)\n  URL: %s\n  ID: %d\n\n",
			repo.ProjectName, repo.NameSpace, repo.ProjectHttpUrl, repo.ProjectId)
	}

	return &MCPToolResult{
		Success: true,
		Content: content,
		Data:    repos,
	}
}

func handleSearchGitlabRepos(c *lib.GinContext, args map[string]interface{}) *MCPToolResult {
	text := getStringParam(args, "text", "")
	if text == "" {
		return createErrorResult("搜索文本不能为空")
	}

	var repos []model.GitlabRepo
	result := model.DB().Where("project_http_url LIKE ?", "%"+text+"%").Find(&repos)
	if result.Error != nil {
		return createErrorResult("搜索失败: " + result.Error.Error())
	}

	content := fmt.Sprintf("搜索 '%s' 找到 %d 个项目:\n\n", text, len(repos))
	for _, repo := range repos {
		content += fmt.Sprintf("- **%s**\n  URL: %s\n\n", repo.ProjectName, repo.ProjectHttpUrl)
	}

	return &MCPToolResult{
		Success: true,
		Content: content,
		Data:    repos,
	}
}

// Jenkins相关处理器

func handleGetJenkinsBuilds(c *lib.GinContext, args map[string]interface{}) *MCPToolResult {
	limit := getIntParam(args, "limit", 5)
	appName := getStringParam(args, "app_name", "")
	status := getStringParam(args, "status", "")

	var builds []model.JenkinsJobBuild
	db := model.DB().Limit(limit).Order("id desc")

	if appName != "" {
		db = db.Where("app like ?", "%"+appName+"%")
	}
	if status != "" {
		db = db.Where("status = ?", status)
	}

	result := db.Find(&builds)
	if result.Error != nil {
		return createErrorResult("数据库查询失败: " + result.Error.Error())
	}

	content := fmt.Sprintf("找到 %d 个Jenkins构建记录:\n\n", len(builds))
	for _, build := range builds {
		content += fmt.Sprintf("- **任务**: %s\n  **状态**: %s\n  **构建号**: %d\n  **分支**: %s\n  **时间**: %s\n  **环境**: %s\n\n",
			build.JobName, build.Status, build.BuildNumber, build.Branch, build.Time, build.Env)
	}

	return &MCPToolResult{
		Success: true,
		Content: content,
		Data:    builds,
	}
}

func handleTriggerPipeline(c *lib.GinContext, args map[string]interface{}) *MCPToolResult {
	jobName := getStringParam(args, "job_name", "")
	if jobName == "" {
		return createErrorResult("任务名称不能为空")
	}

	branch := getStringParam(args, "branch", "master")
	parameters, _ := args["parameters"].(map[string]interface{})

	// 这里应该实现实际的Jenkins构建触发逻辑
	// 为了演示，返回模拟结果
	content := fmt.Sprintf("已准备触发Jenkins流水线构建:\n\n**任务名称**: %s\n**分支**: %s\n", jobName, branch)

	if parameters != nil && len(parameters) > 0 {
		content += "**构建参数**:\n"
		for key, value := range parameters {
			content += fmt.Sprintf("  - %s: %v\n", key, value)
		}
	}

	content += "\n注意：实际构建触发需要通过Jenkins API实现。"

	return &MCPToolResult{
		Success: true,
		Content: content,
		Data: map[string]interface{}{
			"job_name":   jobName,
			"branch":     branch,
			"parameters": parameters,
			"status":     "prepared",
		},
	}
}

// 服务器管理处理器

func handleGetServerList(c *lib.GinContext, args map[string]interface{}) *MCPToolResult {
	limit := getIntParam(args, "limit", 10)
	osType := getStringParam(args, "os_type", "")

	var servers []model.Server
	db := model.DB().Limit(limit)

	if osType != "" {
		db = db.Where("os_type = ?", osType)
	}

	result := db.Find(&servers)
	if result.Error != nil {
		return createErrorResult("数据库查询失败: " + result.Error.Error())
	}

	content := fmt.Sprintf("找到 %d 个服务器:\n\n", len(servers))
	for _, server := range servers {
		content += fmt.Sprintf("- **ID**: %d\n  **IP**: %s\n  **用户名**: %s\n  **端口**: %d\n  **系统**: %s\n\n",
			server.Id, server.Ip, server.Username, server.Port, server.OsType)
	}

	return &MCPToolResult{
		Success: true,
		Content: content,
		Data:    servers,
	}
}

func handleSSHExecuteCommand(c *lib.GinContext, args map[string]interface{}) *MCPToolResult {
	serverIdFloat, ok := args["server_id"].(float64)
	if !ok {
		return createErrorResult("缺少或无效的server_id参数")
	}
	serverId := int64(serverIdFloat)

	command := getStringParam(args, "command", "")
	if command == "" {
		return createErrorResult("命令不能为空")
	}

	timeout := getIntParam(args, "timeout", 30)

	// 查询服务器信息
	var server model.Server
	result := model.DB().Where("id = ?", serverId).First(&server)
	if result.Error != nil {
		return createErrorResult("服务器不存在")
	}

	// 这里应该实现实际的SSH命令执行逻辑
	content := fmt.Sprintf("准备在服务器执行SSH命令:\n\n**服务器**: %s (%s)\n**命令**: %s\n**超时**: %d秒\n\n注意：出于安全考虑，实际命令执行需要通过WebSocket SSH连接进行。",
		server.Ip, server.Username, command, timeout)

	return &MCPToolResult{
		Success: true,
		Content: content,
		Data: map[string]interface{}{
			"server_id": serverId,
			"server_ip": server.Ip,
			"command":   command,
			"timeout":   timeout,
			"status":    "prepared",
		},
	}
}

// 系统监控处理器

func handleGetSystemStatus(c *lib.GinContext, args map[string]interface{}) *MCPToolResult {
	detailed := getBoolParam(args, "detailed", false)

	// 检查数据库连接
	dbStatus := "connected"
	if err := model.DB().Exec("SELECT 1").Error; err != nil {
		dbStatus = "disconnected: " + err.Error()
	}

	// 检查Jenkins连接
	jenkinsStatus := "connected"
	if model.JenkinsConnection == nil {
		jenkinsStatus = "not configured"
	}

	content := fmt.Sprintf(`系统状态报告:

**数据库状态**: %s
**Jenkins状态**: %s
`,
		dbStatus, jenkinsStatus)

	if detailed {
		content += fmt.Sprintf(`
**详细配置信息**:
- GitLab API: %s
- Jenkins URL: %s
- 基础路径: %s
- 仓库URL: %s
`,
			model.C.General.GitlabApiUrl, model.C.General.JenkinsUrl,
			model.C.General.BasePath, model.C.General.RepoUrl)
	}

	content += "\n系统运行正常。"

	return &MCPToolResult{
		Success: true,
		Content: content,
		Data: map[string]interface{}{
			"database_status": dbStatus,
			"jenkins_status":  jenkinsStatus,
			"detailed":        detailed,
		},
	}
}

// 工作流处理器

func handleGetWorkflowInstances(c *lib.GinContext, args map[string]interface{}) *MCPToolResult {
	limit := getIntParam(args, "limit", 10)
	status := getStringParam(args, "status", "")

	var instances []model.WorkflowInstance
	db := model.DB().Limit(limit).Order("id desc")

	if status != "" {
		db = db.Where("status = ?", status)
	}

	result := db.Find(&instances)
	if result.Error != nil {
		return createErrorResult("数据库查询失败: " + result.Error.Error())
	}

	content := fmt.Sprintf("找到 %d 个工作流实例:\n\n", len(instances))
	for _, instance := range instances {
		content += fmt.Sprintf("- **ID**: %d\n  **名称**: %s\n  **状态**: %s\n  **创建者**: %s\n\n",
			instance.Id, instance.WorkflowName, instance.Status, instance.Creator)
	}

	return &MCPToolResult{
		Success: true,
		Content: content,
		Data:    instances,
	}
}

// 辅助函数

func getStringParam(args map[string]interface{}, key, defaultValue string) string {
	if value, ok := args[key].(string); ok {
		return value
	}
	return defaultValue
}

func getIntParam(args map[string]interface{}, key string, defaultValue int) int {
	if value, ok := args[key].(float64); ok {
		return int(value)
	}
	if value, ok := args[key].(int); ok {
		return value
	}
	if value, ok := args[key].(string); ok {
		if intValue, err := strconv.Atoi(value); err == nil {
			return intValue
		}
	}
	return defaultValue
}

func getBoolParam(args map[string]interface{}, key string, defaultValue bool) bool {
	if value, ok := args[key].(bool); ok {
		return value
	}
	return defaultValue
}

func createErrorResult(message string) *MCPToolResult {
	return &MCPToolResult{
		Success: false,
		Error:   message,
	}
}
